package com.cbwl.eoas.web.framework.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.cbwl.eoas.common.framework.exception.CustomException;
import com.cbwl.eoas.common.framework.utils.ExceptionUtils;


/**
 * 
 * <p>[描述信息：自定义异常解析类]</p>
 *
 * @author 虞云波 - yuyunbo@3856.cc
 * @version 1.0 Created on 2017年9月29日 下午4:20:07
 */
public class CommHandlerExceptionResolver implements HandlerExceptionResolver {

	private static Logger LOG = LoggerFactory.getLogger(CommHandlerExceptionResolver.class);

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		// 是否为ajax请求
		String requestType = request.getHeader("X-Requested-With");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("exception", exception);
		String exceptionstr = ExceptionUtils.getTrace(exception);
		LOG.error(exceptionstr);
		if (exception instanceof AuthorizationException) {
			if ("XMLHttpRequest".equals(requestType)) {
				response.setStatus(1000);
				response.setContentType("text/html;charset=utf-8");
				return new ModelAndView();
			}
			return new ModelAndView("forward:/login/loginout.html");
		}
		
		if (exception instanceof CustomException) {
			request.setAttribute("errorCode", ((CustomException) exception).getCode());
			request.setAttribute("errorMsg", ((CustomException) exception).getMsg());
			data.put("errorCode", ((CustomException) exception).getCode());
			data.put("errorMsg", ((CustomException) exception).getMsg());
			if ("XMLHttpRequest".equals(requestType)) {
				response.setStatus(999);
				try {
					PrintWriter writer = response.getWriter();
					writer.write("错误提示[" + ((CustomException) exception).getCode() + "]："
							+ ((CustomException) exception).getMsg());
					writer.flush();
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
			return new ModelAndView("forward:/exception/initSystemException.html");
		}
		
		request.setAttribute("errorCode", "CBWL-000000");
		request.setAttribute("errorMsg","很抱歉，系统暂时无法处理您的请求");
		request.setAttribute("exceptionstr_detail",exceptionstr);
		return new ModelAndView("forward:/exception/initSystemException.html");
	}
}
